package com.xiaojian.blog.interceptor;

import com.xiaojian.blog.constant.WebConstant;
import com.xiaojian.blog.dto.Types;
import com.xiaojian.blog.model.OptionPO;
import com.xiaojian.blog.model.UserPO;
import com.xiaojian.blog.service.OptionService;
import com.xiaojian.blog.service.UserService;
import com.xiaojian.blog.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器,在请求到达controller之前拦截
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseInterceptor.class);
    private static final String USER_AGENT = "user-agent";


    @Resource
    private UserService userService;

    @Resource
    private OptionService optionService;

    @Resource
    private Commons commons;

    @Resource
    private AdminCommons adminCommons;


    private MapCache cache = MapCache.single();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();

        LOGGER.info("UserAgent: {}", request.getHeader("USER_AGENT"));
        LOGGER.info("用户访问地址: {}, 来路地址: {}", uri, IPKit.getIpAddrByRequest(request));

        //请求拦截处理
        UserPO userPO = TaleUtils.getLoginUser(request);
        if (null == userPO) {
            Integer uid = TaleUtils.getCookieUid(request);
            if (null != uid) {
                userPO = userService.queryUserById(uid);
                request.getSession().setAttribute(WebConstant.LOGIN_SESSION_KEY, userPO);
            }
        }
        if (uri.startsWith("/admin") && !uri.startsWith("/admin/login") && null == userPO) {
            //重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/admin/login");
            return false;
        }
        //设置get请求的token
        if (request.getMethod().equals("GET")) {
            String csrf_token = UUID.UU64();
            //默认存储30分钟
            cache.hset(Types.CSRF_TOKEN.getType(), csrf_token, uri, 30 * 60);
            request.setAttribute("_csrf_token", csrf_token);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        OptionPO optionPO = optionService.getOptionByName("site_record");
        httpServletRequest.setAttribute("commons", commons);//一些工具类和方法
        httpServletRequest.setAttribute("option", optionPO);
        httpServletRequest.setAttribute("adminCommons", adminCommons);

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
